<?php

class Search extends Database {

    public $form_table;
    public $form_viewers;
    public $form_id;

    //FOR GET/SEARCH REQUEST

    public function getManyRequest($search_value, $fields, $id, $limit_start, $limit_end, $obj) {
        //get form table
        $this->getFormTable($id);
        $this->form_id = $id;
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];

        if ($fields != "0") {
            if ($fields == "Requestor") {
                $search = "WHERE (u.first_name LIKE '%" . $search_value . "%' OR u.last_name LIKE '%" . $search_value . "%' OR CONCAT_WS( ' ', u.first_name, u.last_name) LIKE  '%" . $search_value . "%')";
            } else if ($fields == "Processor") {
                $search = "WHERE (up.first_name LIKE '%" . $search_value . "%' OR up.last_name LIKE '%" . $search_value . "%' OR CONCAT_WS( ' ', up.first_name, up.last_name) LIKE  '%" . $search_value . "%')";
            } else if ($fields == "ID") {
                $search = "WHERE (form.ID = " . $search_value . ")";
            } else {
                $search = "WHERE (form.$fields LIKE '%" . $search_value . "%')";
            }
        } else {
            $search = "WHERE (";
            //get active fields
            $active_fields = functions::getFormFields($id);
            foreach ($active_fields as $value) {
                if ($value) {
                    $search.= "form.$value LIKE  '%" . $search_value . "%' OR ";
                }
            }
            $search .= " TrackNo LIKE  '%" . $search_value . "%' OR (u.first_name LIKE '%" . $search_value . "%' OR u.last_name LIKE '%" . $search_value . "%') OR 
                    (up.first_name LIKE '%" . $search_value . "%' OR up.last_name LIKE '%" . $search_value . "%' OR CONCAT_WS( ' ', up.first_name, up.last_name) LIKE  '%" . $search_value . "%') OR form.Status LIKE  '%" . $search_value . "%')";
            // $search .= " TrackNo LIKE  '%".$search_value."%' OR Requestor LIKE  '%".$search_value."%' OR 
            //         Processor LIKE  '%".$search_value."%' OR Status LIKE  '%".$search_value."%')";
        }
        $limit = " LIMIT $limit_start, $limit_end";
        if ($limit_end == "" && $limit_end == "") {
            $limit = "";
        }
        if($obj['multi_search']){
            $search .= $obj['multi_search'];
        }
        if ($obj['date_range']) {
            $search .= " AND (" . $obj['date_field'] . " between '" . $obj['date_from'] . "' and '" . $obj['date_to'] . "')";
        }
        $sort = "";
        if($obj['column-sort']){
            $sort = "ORDER BY A.".$obj['column-sort']." ".$_POST['column-sort-type'];
        }else{
            $sort = "ORDER BY A.ID DESC";
        }
        if($obj['condition']){
            $search .= $obj['condition'];
        }

        $readers = $this->getFormPrivacyUsers($this->form_viewers);
        //execute query
        $query_str = "SELECT  * FROM (SELECT form.id as request_id, u.first_name,u.last_name,u.middle_name, form.Status as form_status,
                    form.Requestor as requestor_id, form.Processor as processors_id, up.last_name as processor_lastname, form.*, '" . $readers . "' as IsReader , CONCAT_WS(' ',u.first_name, u.last_name) as requestorName
                    FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor LEFT JOIN tbuser up on up.id = form.processor
                     $search) A WHERE (A.IsReader = '1' OR A.Requestor = " . $auth['id'] . " OR  FIND_IN_SET(" . $auth['id'] . ",A.Processor) OR FIND_IN_SET(" . $auth['id'] . ",A.Editor) OR FIND_IN_SET(" . $auth['id'] . ",A.Viewer)
                     OR EXISTS(SELECT * FROM tbrequest_viewer mention WHERE mention.user_id=" . $auth['id'] . " 
                        AND mention.request_id = A.request_id AND mention.form_id=" . $this->form_id . ")
                     ) $sort $limit";

//        print_r($query_str);
        $query_count = "SELECT  count(*) as count FROM (SELECT form.Requestor, form.Processor, form.Editor, form.Viewer,'" . $readers . "' as IsReader , form.id as request_id
                   FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor LEFT JOIN tbuser up on up.id = form.processor
                    $search) A WHERE (A.IsReader = '1' OR A.Requestor = " . $auth['id'] . " OR  FIND_IN_SET(" . $auth['id'] . ",A.Processor) OR FIND_IN_SET(" . $auth['id'] . ",A.Editor) OR FIND_IN_SET(" . $auth['id'] . ",A.Viewer)
                    OR EXISTS(SELECT * FROM tbrequest_viewer mention WHERE mention.user_id=" . $auth['id'] . " 
                       AND mention.request_id = A.request_id AND mention.form_id=" . $this->form_id . ")
                    )";
        $count = $this->query($query_count, "row");
        // $count = "124526";
        $count = $count['count'];



        $getRequest = $this->query($query_str, "array");
        // $count = count($getRequest);
        
        $returnRequest = array();
        foreach ($getRequest as $request) {
            $processors = explode(",", $request['processors_id']);

            $processor_bool = array_search($userID, $processors) . "";

            $request_viewer = $this->requestViewer($request['request_id']);

            // if (/*$processor_bool != "" || $request['requestor_id'] == $userID || $readers ||*/ $request_viewer) {
            $array_starred = array("starred" => "0");
            $buttons = array("buttons" => "");
            $hasStarred = $this->getStarred($request['request_id']);

            if ($hasStarred > 0) {
                $array_starred = array("starred" => $hasStarred);
            }

            //check if current user is one of the processors
            $cancel_button = array("Cancel" =>
                array(
                    "button_name" => "Cancel",
                    "child_id" => "Cancel",
                    "parent_id" => "Cancel",
                    // "require_comment" => false,
                    // "wokflow_button_line_color" => "424242"
            ));

            if ($processor_bool != "") {
                if ($request['requestor_id'] == $userID && $request['LastAction'] != '') {
                    $button_arr = json_decode($request['LastAction'], true);
                    $button_arr['Cancel'] = $cancel_button['Cancel'];
                    $buttons = array("buttons" => json_encode($button_arr));
                } else {
                    $buttons = array("buttons" => $request['LastAction']);
                }
            } else if ($request['requestor_id'] == $userID && $request['LastAction'] != '') {
                $buttons = array("buttons" => json_encode($cancel_button));
            }

            array_push($request, $array_starred);
            array_push($request, array("user_image" => post::avatarPic("tbuser", $request['requestor_id'], "50", "50", "small", "avatar")));
            array_push($request, $buttons);
            array_push($request, array("count" => $count));
            array_push($returnRequest, $request);
            // }
        }

        return $returnRequest;
        // return $query_str;
        // return $query_count;
    }

    //GET REQUESTvIEWER 
    public function requestViewer($request_id) {
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];

        $query_count = $this->query("SELECT * FROM tbrequest_viewer WHERE user_id = '$userID' AND request_id = '$request_id' AND form_id = '$this->form_id'", "numrows");
        if ($query_count > 0) {
            return true;
        }
    }

    //FOR OWN REQUEST
    public function countOwnRequest($id) {
        //get form table
        $this->getFormTable($id);
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];


        //execute query
        $query_str = "SELECT count(*) as countData
                    FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor
                    WHERE form.requestor = '$userID'";



        $getRequest = $this->query($query_str, "row");

        return $getRequest['countData'];
    }

    //FOR OWN REQUEST
    public function getOwnRequest($id, $limit_start, $limit_end, $search_value) {
        //get form table
        $this->getFormTable($id);
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];
        $limit = " LIMIT $limit_start, $limit_end";
        if ($limit_end == "" && $limit_end == "") {
            $limit = "";
        }


        //execute query
        $query_str = "SELECT form.DateCreated as DateCreated, form.TrackNo as TrackNo,form.id as request_id, u.first_name,u.last_name,u.middle_name, form.Status as form_status,
                    form.Requestor as requestor_id, form.Processor as processors_id 
                    FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor, tb_workspace tbw
                    WHERE form.requestor = '$userID' AND tbw.id = $id AND (tbw.form_name LIKE '%" . $search_value . "%' OR form.TrackNo LIKE '%" . $search_value . "%' OR form.Status LIKE '%" . $search_value . "%') ORDER BY form.id DESC $limit";



        $getRequest = $this->query($query_str, "array");
        $readers = $this->getFormPrivacyUsers($this->form_viewers);
        $returnRequest = array();
        foreach ($getRequest as $request) {
            $processors = explode(",", $request['processors_id']);

            $processor_bool = array_search($userID, $processors) . "";

            //if($processor_bool != "" || $request['requestor_id'] == $userID || $readers){
            $array_starred = array("starred" => "0");
            $hasStarred = $this->getStarred($request['request_id']);
            if ($hasStarred > 0) {
                $array_starred = array("starred" => $hasStarred);
            }

            array_push($request, $array_starred);
            array_push($returnRequest, $request);
            //}
        }

        return $returnRequest;
    }

    //FOR Starred request
    public function countStarredRequests($id) {
        //get form table
        $this->getFormTable($id);
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];
        $ctr = 0;

        //execute query
        if ($id == 0) {
            $query_str = "SELECT count(*) as countData
                    FROM `tbpost` form LEFT JOIN tbuser u ON u.id=form.postedBy, tbstarred tbs 
                    WHERE tbs.tablename = 'tbpost' and tbs.data_id = form.id and tbs.user_id = $userID";
            $getRequest = $this->query($query_str, "row");
            $ctr = $getRequest['countData'];
        } else {
            $query_str = "SELECT count(*) as countData
                        FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor, tbstarred tbs 
                        WHERE tbs.tablename = '$this->form_table' and tbs.data_id = form.id and tbs.user_id = $userID";

            $getRequest = $this->query($query_str, "row");

            $ctr = $getRequest['countData'];
        }

        return $ctr;
    }

    public function getStarredRequests($id, $limit_start, $limit_end) {
        //get form table
        $this->getFormTable($id);

        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];

        $limit = " LIMIT $limit_start, $limit_end";
        if ($limit_end == "" && $limit_end == "") {
            $limit = "";
        }
        $returnRequest = array();
        if ($id == 0) {
            $query_str = "SELECT tbs.*, p.postedBy as requestor_id, u.first_name,u.last_name,u.middle_name, p.date_posted as DateCreated FROM tbstarred tbs, tbpost p LEFT JOIN tbuser u ON u.id=p.postedBy WHERE tbs.tablename = 'tbpost' and tbs.data_id = p.id and tbs.user_id = $userID ORDER BY p.id DESC  $limit";
            // echo $query_str;
            $getPost = $this->query($query_str, "array");
            foreach ($getPost as $post) {
                $array_starred = array("starred" => "0", "link" => functions::base_encode_decode("encrypt", $post['data_id']));
                array_push($post, $array_starred);
                array_push($returnRequest, $post);
            }
        } else {
            //execute query
            $query_str = "SELECT tbs.type, form.DateCreated as DateCreated, form.TrackNo as TrackNo,form.id as request_id, u.first_name,u.last_name,u.middle_name, form.Status as form_status,
                        form.Requestor as requestor_id, form.Processor as processors_id,tbs.* 
                        FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor, tbstarred tbs 
                        WHERE tbs.tablename = '$this->form_table' and tbs.data_id = form.id and tbs.user_id = $userID
                         ORDER BY form.id DESC  $limit";

            $readers = $this->getFormPrivacyUsers($this->form_viewers);

            $getRequest = $this->query($query_str, "array");


            foreach ($getRequest as $request) {
                $processors = explode(",", $request['processors_id']);

                $processor_bool = array_search($userID, $processors) . "";

                if ($processor_bool != "" || $request['requestor_id'] == $userID || $readers) {
                    $array_starred = array("starred" => "0");
                    // $hasStarred = $this->getStarred($request['request_id']);
                    // if($hasStarred>0){
                    //     $array_starred = array("starred"=>$hasStarred);
                    // }

                    array_push($request, $array_starred);
                    array_push($returnRequest, $request);
                }
            }
        }


        return $returnRequest;
    }

    public function getStarred($request_id) {
        $auth = Auth::getAuth('current_user');
        $userID = $auth['id'];
        $tablename = $this->form_table;
        $strSQL = "SELECT * FROM tbstarred WHERE tablename = '$tablename' AND data_id = $request_id AND user_id = '$userID'";
        $starred = $this->query($strSQL, "row");
        return $starred['id'];
    }

    // public function getOwnRequest($search_value,$fields,$id){
    //     //get form table
    //     $this->getFormTable($id);
    //     $auth = Auth::getAuth('current_user');
    //     $userID = $auth['id'];
    //     if($fields!="0"){
    //         $search = "WHERE ($fields LIKE '%".$search_value."%')";
    //     }else{
    //         $search = "WHERE ("; 
    //         //get active fields
    //         $active_fields = functions::getFormFields($id);
    //         foreach ($active_fields as $value) {
    //            //echo "<option value='". $value ."'>". $value ."</option>";
    //             if($value){
    //                 $search.= "$value LIKE  '%".$search_value."%' OR ";
    //             }
    //         }
    //         $search .= " TrackNo LIKE  '%".$search_value."%' OR Requestor LIKE  '%".$search_value."%' OR 
    //                 Processor LIKE  '%".$search_value."%' OR Status LIKE  '%".$search_value."%')";
    //     }
    //     //execute query
    //     $query_str = "SELECT form.DateCreated as DateCreated, form.TrackNo as TrackNo,form.id as request_id, u.first_name,u.last_name,u.middle_name, form.Status as form_status,
    //                 form.Requestor as requestor_id, form.Processor as processors_id 
    //                 FROM `$this->form_table` form LEFT JOIN tbuser u ON u.id=form.requestor $search AND form.Requestor = {$this->escape($userID)} ORDER BY form.id DESC";
    //     $readers = $this->getFormPrivacyUsers($this->form_viewers);
    //     $getRequest = $this->query($query_str,"array");
    //     return $getRequest;
    // }

    public function getCompaniesForm($others) {
        $auth = Auth::getAuth('current_user');
        $strSQL = "SELECT id,form_name,form_table_name FROM tb_workspace WHERE company_id = {$this->escape($auth['company_id'])} $others";
        $getForms = $this->query($strSQL, "array");
        return $getForms;
    }

    public function getFormTable($id) {
        $query_str = "SELECT * FROM tb_workspace WHERE id = {$this->escape($id)}";
        $getData = $this->query($query_str, "row");
        $this->form_table = $getData['form_table_name'];


        $this->form_viewers = $getData['form_viewers'];
    }

    //FOR ORGCHART

    public function getOrgchart($search, $start,$json) {

        $auth = Auth::getAuth('current_user');
        $limit = "";
        if ($start != "") {
            $limit = "LIMIT $start , 10";
        }
        
        $orderBy = " ORDER BY status DESC, date DESC ";
        if($json['column-sort']!=""){
          $orderBy = " ORDER BY ".$json['column-sort']." ".$json['column-sort-type'];
        }

        $condition = "";
        if($json['condition']){
            $condition = $json['condition'];
        }

        $query_str = "SELECT * FROM tborgchart WHERE company_id={$this->escape($auth['company_id'])} AND is_active={$this->escape(1)} AND title LIKE '%$search%' $condition $orderBy $limit";
        $getOrgchart = $this->query($query_str, "array");
        return $getOrgchart;
    }

    public function countOrgchart(){
        $auth = Auth::getAuth('current_user');
        $query_str = "SELECT count(1) as count FROM tborgchart WHERE company_id={$this->escape($auth['company_id'])} AND is_active={$this->escape(1)}";
        $getOrgchart = $this->query($query_str, "row");
        return $getOrgchart['count'];
    }

    public function getForms($search, $start,$json) {
        $auth = Auth::getAuth('current_user');
        $limit = "";
        if ($start != "") {
            $limit = "LIMIT $start , 10";
        }
        $orderBy = " ORDER BY w.is_active DESC, date_created DESC ";
        if($json['column-sort']!=""){
            if($json['column-sort']=="is_active"){
                $json['column-sort'] = "w.is_active";
            }
          $orderBy = " ORDER BY ".$json['column-sort']." ".$json['column-sort-type'];
        }

        $condition = "";
        if($json['condition']){
            $condition = $json['condition'];
        }

        $query_str = "SELECT *,w.id as wsID,w.form_admin,w.created_by,w.is_active as ws_status FROM tb_workspace w
                                   LEFT JOIN tbuser u on u.id=w.created_by
                                   WHERE w.company_id={$this->escape($auth['company_id'])} AND w.form_name LIKE '%$search%' $condition $orderBy $limit";
        
        $getForms = $this->query($query_str, "array");
        return $getForms;
    }

    public function countForms(){
        $auth = Auth::getAuth('current_user');
        $query_str = "SELECT count(1) as count FROM tb_workspace w
                                   LEFT JOIN tbuser u on u.id=w.created_by
                                   WHERE w.company_id={$this->escape($auth['company_id'])}";
        $getForms = $this->query($query_str, "row");
        return $getForms['count'];
    }

    public function getPrintReports($selector) {
        $result = $this->query("SELECT * FROM tb_generate " . $selector, 'array');
        return $result;
    }

    public function getSpecificForms($array) {
        $cond_string = "";
        foreach ($array as $field => $value) {
            $cond_string .= $field . "=" . $this->escape($value) . " AND ";
        }
        $cond_string = substr($cond_string, 0, strlen($cond_string) - 4);
        $auth = Auth::getAuth('current_user');
        $query_str = "SELECT *,w.id as wsID,w.is_active as ws_status FROM tb_workspace w
                                   LEFT JOIN tbuser u on u.id=w.created_by
                                   WHERE $cond_string";
        $getForms = $this->query($query_str, "array");
        return $getForms;
    }

    public function getWorkflows($search, $start,$json) {
        $auth = Auth::getAuth('current_user');
        $limit = "";
        if ($start != "") {
            $limit = "LIMIT $start , 10";
        }
        $orderBy = " ORDER BY Is_Active DESC, date DESC ";
        if($json['column-sort']!=""){
          $orderBy = " ORDER BY ".$json['column-sort']." ".$json['column-sort-type'];
        }
        $condition = "";
        if($json['condition']){
            $condition = $json['condition'];
        }

        $getWorkflow = $this->query("SELECT ws.id as ws_id, wf.date as wf_date,ws.form_admin,ws.created_by,
                                          wf.id as wf_id, wf.title as wf_title, wf.form_id as form_id, wf.is_active as Is_Active, ws.form_name as form_name 
                                          FROM tbworkflow wf LEFT JOIN tb_workspace ws on wf.form_id = ws.id WHERE ws.company_id={$this->escape($auth['company_id'])} 
                                          AND (wf.title LIKE '%$search%' OR ws.form_name LIKE '%$search%') $condition  $orderBy $limit", "array");
        return $getWorkflow;
    }

    //FOR DEPARTMENT
    public function getAllDepartment() {
        $auth = Auth::getAuth('current_user');
        $getDepartment = $this->query("SELECT oo.id,oo.department FROM tborgchart o LEFT JOIN tborgchartobjects oo ON o.id = oo.orgchart_id WHERE o.status = 1 AND o.company_id={$this->escape($auth['company_id'])}", "array");
        return $getDepartment;
    }

    //FOR POSITION
    public function getAllPosition() {
        $auth = Auth::getAuth('current_user');
        $getPosition = $this->query("SELECT DISTINCT(position) FROM tbuser WHERE  is_active = 1 AND company_id={$this->escape($auth['company_id'])}", "array");
        return $getPosition;
    }

    //FOR POSITION
    public function getAllGroups() {
        $auth = Auth::getAuth('current_user');
        $getGroups = $this->query("SELECT * FROM tbgroups WHERE  is_active = 1 AND user_id={$this->escape($auth['id'])}", "array");
        return $getGroups;
    }

    //FOR USERS
    public function getAllUsers($str) {
        $auth = Auth::getAuth('current_user');
        $getUsers = $this->query("SELECT id,first_name,last_name FROM tbuser WHERE is_active = 1 AND company_id={$this->escape($auth['company_id'])} $str", "array");
        return $getUsers;
    }

    //form privacy
    public function getFormPrivacyUsers($json) {
        $auth = Auth::getAuth('current_user');
        $form_authors = json_decode($json, true);
        //$departments = $form_authors['departments'];
        $count = 0;
        foreach ($form_authors as $key => $value) {
            if ($key == "departments") {
                $search = array_search($auth['department_id'], $value) . "";
                if ($search != "") {
                    $count++;
                    break;
                }
            } else if ($key == "positions") {
                $search = array_search($auth['position'], $value) . "";
                if ($search != "") {
                    $count++;
                    break;
                }
            } else if ($key == "users") {
                $search = array_search($auth['id'], $value) . "";
                if ($search != "") {
                    $count++;
                    break;
                }
            }
        }
        if ($count > 0) {
            return true;
        }
    }

    public function getFormPrivacyOtherUsers($json,$id) {
        $getUserData = $this->query("SELECT * FROM tbuser WHERE id = $id","row");
        $form_authors = json_decode($json, true);
        //$departments = $form_authors['departments'];
        $count = 0;
        foreach ($form_authors as $key => $value) {
            if ($key == "departments") {
                $count = 0;
                $search = array_search($getUserData['department_id'], $value) . "";
                if ($search != "") {
                    $count++;
                    // break;
                }
            } else if ($key == "positions") {
                $count = 0;
                $search = array_search($getUserData['position'], $value) . "";
                if ($search != "") {
                    $count++;
                    // break;
                }
            } else if ($key == "users") {
                $count = 0;
                $search = array_search($getUserData['id'], $value) . "";
                if ($search != "") {
                    $count++;
                    // break;
                }
            }
        }
        if ($count > 0) {
            return true;
        }
    }


    public function getCategory($id) {
        $auth = Auth::getAuth('current_user');
        $company_id = $auth['company_id'];
        $getcategory = $this->query("SELECT * FROM tbform_category WHERE company_id = $company_id && id = $id", "array");
        return $getcategory;
    }

    public function countCategory() {
        $auth = Auth::getAuth('current_user');
        $company_id = $auth['company_id'];
        // get category that are using
        $forms_array = $this->query("SELECT ws.form_name as form_name, ws.id as id, ws.form_json as form_json
                                              FROM tb_workspace ws
                                              LEFT JOIN tbworkflow wf on ws.id = wf.form_id
                                              WHERE wf.is_active = 1 and ws.is_active = 1
                                              AND company_id = {$this->escape($auth[company_id])}
                                              ORDER BY ws.form_name DESC", "array");

        $array_categoryID = array();
        foreach ($forms_array as $forms) {
            $json = json_decode($forms['form_json'], true);
            $formID = $forms['id'];
            $formName = $forms['form_name'];
            $forms = $json['form_json'];
            $categoryID = $json['categoryName'];

            array_push($array_categoryID, $categoryID);
        }
        $getcategory = $this->query("SELECT * FROM tbform_category WHERE company_id = $company_id", "array");
        $ctr = 0;
        $categoryIDReturn = array();
        foreach ($getcategory as $category) {
            if ($category['users'] != "") {
                if ($this->getFormPrivacyUsers($category['users']) == false) {
                    continue;
                }
            }
            if (in_array($category['id'], $array_categoryID)) {
                $categoryIDReturn[] = $category['id'];
            }
        }
        if (in_array("0", $array_categoryID)) {
            $categoryIDReturn[] = 0;
        }
        return $categoryIDReturn;
    }

    public function getActiveOrgchart(){
        $auth = Auth::getAuth('current_user');
        $company_id = $auth['company_id'];
        $orgchart = $this->query("SELECT * FROM tborgchart tbo WHERE tbo.company_id = {$this->escape($company_id)} and tbo.status = '1' and tbo.is_active = 1","array");

        return $orgchart;
    }

}
function array_insert(&$array,$element,$position=null) {
      if (count($array) == 0) {
        $array[] = $element;
      }
      elseif (is_numeric($position) && $position < 0) {
        if((count($array)+position) < 0) {
          $array = array_insert($array,$element,0);
        }
        else {
          $array[count($array)+$position] = $element;
        }
      }
      elseif (is_numeric($position) && isset($array[$position])) {
        $part1 = array_slice($array,0,$position,true);
        $part2 = array_slice($array,$position,null,true);
        $array = array_merge($part1,array($position=>$element),$part2);
        foreach($array as $key=>$item) {
          if (is_null($item)) {
            unset($array[$key]);
          }
        }
      }
      elseif (is_null($position)) {
        $array[] = $element;
      }  
      elseif (!isset($array[$position])) {
        $array[$position] = $element;
      }
      $array = array_merge($array);
      return $array;
}
function getValidHeaderFields($fields_headerObj,$getCustomView,$fields_headerObjType){
    
    $fields_headerObjDecodedTrue = json_decode(json_encode($fields_headerObj),true);

    
    if($fields_headerObjType=="1"){

        $defaultFields = array();
        $customView = array();

        //migrate to default tupe of array not std
        
        
        //count of defaultFields
        $otherFieldsStartPos = count($defaultFields);

        //insert default fields in saved header
        foreach ($defaultFields as $defaultFields_value) {
            array_insert($fields_headerObjDecodedTrue,$defaultFields_value,$otherFieldsStartPos);
            $otherFieldsStartPos++;
        }
        
        //push valid header in custom view
        $customView = combineColumnHeaderInfo($getCustomView[0]['json'],$fields_headerObjDecodedTrue);

    }else if($fields_headerObjType=="0"){
        $customView = array();
        // FOR DEFAULT COLUMN
        $defaultFields = array(array("field_label" => "Tracking Number", "field_name" => "TrackNo"), array("field_label" => "Requestor", "field_name" => "requestorName"), array("field_label" => "Status", "field_name" => "Status"), array("field_label" => "Date Created", "field_name" => "DateCreated"));
        //push valid header in custom view
        $customView = combineColumnHeaderInfo($getCustomView[0]['json'],$defaultFields);
    }else{

        $defaultFields = array(array("field_label"=>"Tracking Number","field_name"=>"TrackNo"),array("field_label"=>"Requestor","field_name"=>"requestorName"),array("field_label"=>"Status","field_name"=>"Status"),array("field_label"=>"Date Created","field_name"=>"DateCreated"));
        $customView = array();

        //migrate to default tupe of array not std
        $fields_headerObjDecodedTrue = json_decode(json_encode($fields_headerObj),true);
        
        //count of defaultFields
        $otherFieldsStartPos = count($defaultFields);

        //insert default fields in saved header
        foreach ($defaultFields as $defaultFields_value) {
            array_insert($fields_headerObjDecodedTrue,$defaultFields_value,$otherFieldsStartPos);
            $otherFieldsStartPos++;
        }
        $customView = combineColumnHeaderInfo($getCustomView[0]['json'],$fields_headerObjDecodedTrue);
        
    }
    $customView = json_decode(json_encode($customView), true);

    return $customView;
}
function combineColumnHeaderInfo($getCustomView,$fields_headerObjDecodedTrue){
    $customView = array();
    //push valid header in custom view
    $getCustomView = json_decode($getCustomView,true);
    foreach ($getCustomView as $value) {
        foreach ($fields_headerObjDecodedTrue as $value2) {
            if($value['field_name']==$value2['field_name']){
                array_push($customView, $value);
                continue;
            }
        }
    }
    
    $checker = array();
    foreach ($fields_headerObjDecodedTrue as $value2) {
        foreach ($getCustomView as $value) {
            if($value['field_name']==$value2['field_name'] && $value['field_label']==$value2['field_label']){
                array_push($checker, $value);
            }
        }

        if(count($checker) >= 1){

        }else{
            array_push($customView, $value2);
        }
        $checker = array();
    }
    return $customView;
}
?>
